﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.DomainServices.Server;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.RioWCFServices;
using Rio.Framework.Business.Repository;
using System.Configuration;
using Rio.Doc.Business.Repository;

namespace Rio.Applications.Web.Services
{
    public partial class BusinessEntitiesDomainService : DomainService
    {
        #region Query

        /// <summary>
        /// Get OcrMaskList switch folder type
        /// </summary>
        /// <param name="p_lFolderTypeId">Selected Folder type id</param>
        /// <returns>List of OcrMask</returns>
        [Query(HasSideEffects = true)]
        public IEnumerable<OcrMask> GetOcrMaskList(long p_lFolderTypeId)
        {
            return OcrMaskRepository.GetMaskByFolderTypeId(p_lFolderTypeId);
        }


        ///// <summary>
        ///// Process Ocr and return value from any of selected documents and choosen ocrmasks
        ///// </summary>    
        [Query(HasSideEffects = true)]
        public IEnumerable<OcrItem> ProcessOcr(List<string> p_OcrInput, List<long> p_OcrMaskIndex)
        {
            Dictionary<string, List<long>> L_oOcrList = new Dictionary<string, List<long>>();

            List<long> L_o = new List<long>();       
            int L_iFirstIndex;
            int L_iLastIndex;

            // transform the twice list into Dictionnary (filename : Key, OcrMAskId list : Value)
            foreach (string L_oDistincName in p_OcrInput.Distinct())
            {
                L_iFirstIndex = p_OcrInput.IndexOf(L_oDistincName);
                L_iLastIndex = p_OcrInput.LastIndexOf(L_oDistincName);

                for (int i = L_iFirstIndex; i <= L_iLastIndex; i++)
                {
                    L_o.Add(p_OcrMaskIndex[i]);
                }

                L_oOcrList.Add(L_oDistincName, new List<long>(L_o));
                L_o.Clear();
            }

            List<OcrItem> L_oOcrItemList = new List<OcrItem>();

            WCFServiceClient L_oWCFServiceClient = new WCFServiceClient("BasicHttpBinding_IWCFService");

            // Process Ocr and get return ocrmaskitem completed
            foreach (KeyValuePair<string, List<long>> L_oOcrType in L_oOcrList)
            {
                foreach (long L_oOcrMaskId in L_oOcrType.Value)
                {
                    OcrMask L_oOcrMask = OcrMaskRepository.GetMaskById(L_oOcrMaskId);

                    //if ((L_oOcrMask.AuthorArea.Height != -1) && (L_oOcrMask.AuthorArea.Width != -1))
                    //{
                    //    ProcessOcrAreaResponse l_oResponseAuthor = L_oWCFServiceClient.ProcessOcrArea(new ProcessOcrAreaRequest(L_oOcrType.Key, L_oOcrMask.AuthorArea, L_oOcrMask.AuthorOcrType, ((User)HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()]).UserId));
                    //    string L_sAuthorValue = l_oResponseAuthor.ProcessOcrAreaResult;
                    //    L_oOcrItemList.Add(new OcrItem(new Index(){Indentifier = -1}, new List<string>(){L_sAuthorValue}));
                    //}

                    //if ((L_oOcrMask.ChronoNumberArea.Height != -1) && (L_oOcrMask.ChronoNumberArea.Width != -1))
                    //{
                    //    ProcessOcrAreaResponse l_oResponseChrono = L_oWCFServiceClient.ProcessOcrArea(new ProcessOcrAreaRequest(L_oOcrType.Key, L_oOcrMask.ChronoNumberArea, L_oOcrMask.ChronoNumberOcrType, ((User)HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()]).UserId));
                    //    string L_sChronoValue = l_oResponseChrono.ProcessOcrAreaResult;
                    //    L_oOcrItemList.Add(new OcrItem(new Index() { Indentifier = -2 }, new List<string>() { L_sChronoValue }));
                    //}


                    
                    var l_oMessageRequest = new MessageRequest();
                    l_oMessageRequest.LicenseKey = ConfigurationManager.AppSettings.Get("LicenseKey");
                    l_oMessageRequest.EncryptLicense(RioApplicationSettings.LicenseKeyDuration);

                    ProcessOcrResponse l_oResponse = L_oWCFServiceClient.ProcessOcr(new ProcessOcrRequest(L_oOcrType.Key, L_oOcrMask.IndexMaskItemCollection, ((User)HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()]).UserId, l_oMessageRequest));
                    List<OcrMaskItem> L_oOcrMaskItemList = new List<OcrMaskItem>(l_oResponse.ProcessOcrResult);

                    foreach (OcrMaskItem L_oOcrMaskItem in L_oOcrMaskItemList)
                    {
                        L_oOcrItemList.Add(new OcrItem(L_oOcrMaskItem.Index, new List<string>(){L_oOcrMaskItem.OcrValue}));
                    }
                }
            }

            List<string> L_oOcrValueList = new List<string>();
            List<OcrItem> L_oOcrItemListCompile = new List<OcrItem>();
            
            // Combine all result value from an index into one list
            foreach (OcrItem L_oOcrItemDistinct in L_oOcrItemList.Distinct(new OcrItemComparer()))
            {
                foreach (OcrItem L_oOcrItem in L_oOcrItemList)
                {
                    if (L_oOcrItem.OcrIndex.Indentifier == L_oOcrItemDistinct.OcrIndex.Indentifier)
                    {
                        L_oOcrValueList.Add(L_oOcrItem.OcrValueList.First());
                    }
                }
                L_oOcrItemListCompile.Add(new OcrItem(L_oOcrItemDistinct.OcrIndex,new List<string>(L_oOcrValueList)));
                L_oOcrValueList.Clear();
            }


            return L_oOcrItemListCompile;


            //var l_dicFileNameAndRegions = new Dictionary<string, List<OcrMaskItem>>();

            //var l_lstFileNameAndItsRegions = new List<OcrOutput>();
            ////On boucle sur tous les fichiers
            //foreach (var l_sFileName in p_OcrInput.DicOcrInput.Keys)
            //{
            //    var l_lstMaskItemForAFile = new List<OcrMaskItem>();
            //    //On boucle sur tous les identifiant de mask associé au fichier courant
            //    foreach (var l_lMaskId in p_OcrInput.DicOcrInput[l_sFileName])
            //    {
            //        //on boucle sur toutes les régions d'un mask pour les ajouter à la liste
            //        foreach (var ocrMaskItem in OcrMaskRepository.GetRegionByMaskId(l_lMaskId))
            //        {
            //            l_lstMaskItemForAFile.Add(ocrMaskItem);
            //        }
            //    }
            //    l_dicFileNameAndRegions.Add(l_sFileName, l_lstMaskItemForAFile);
            //}

            //WCFServiceClient l_oWCFServiceClient = new WCFServiceClient();
            ////l_oWCFServiceClient.

            ////l_oWCFServiceClient

            ////apel su service
            //return l_lstFileNameAndItsRegions;
            ////List<Dictionary<Dictionary<long, string>, List<string>>> L_oProcessReturn = new List<Dictionary<Dictionary<long, string>, List<string>>>();
            ////L_oProcessReturn.Add(Framework.Ocr.OcrTreatments.ProcessOcr(p_dicFileNameFullPathAndMaskIds));
            ////return L_oProcessReturn;
        }

        #endregion
    }

    /// <summary>
    /// Custom comparer for the OcrItem class
    /// </summary>
    public class OcrItemComparer : IEqualityComparer<OcrItem>
    {
        //Check whether the compared objects reference the same data.
        bool IEqualityComparer<OcrItem>.Equals(OcrItem x, OcrItem y)
        {
            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the products' properties are equal.
            return x.OcrIndex.Indentifier == y.OcrIndex.Indentifier;
        }

        int IEqualityComparer<OcrItem>.GetHashCode(OcrItem obj)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(obj, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashOragnizationIdentifier = obj.Identifier == null ? 0 : obj.Identifier.GetHashCode();

            //Get hash code for the Code field.
            int hashOrganizationCode = obj.Identifier.GetHashCode();

            //Calculate the hash code for the product.
            return hashOragnizationIdentifier ^ hashOrganizationCode;

        }
    }
}